package com.excellent.ImageIdentification;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class AuthUtils {
    private static final String AUTH_URL = "https://aip.baidubce.com/oauth/2.0/token";
    private static final String GRANT_TYPE = "client_credentials";
    private static final String API_KEY = "jCA8TzPI9SpRCxfivGFzh3OA";
    private static final String SECRET_KEY = "xoO4CoPlmoV7alpGCbVzY8fMGYu2VwLI";

    public static String getAccessToken() throws Exception {
        URL url = new URL(AUTH_URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        String authParams = String.format("grant_type=%s&client_id=%s&client_secret=%s", GRANT_TYPE, API_KEY, SECRET_KEY);

        try (OutputStream os = conn.getOutputStream()) {
            byte[] input = authParams.getBytes("utf-8");
            os.write(input, 0, input.length);
        }

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed to get access token");
        }

        // Process the response to extract the access token
        // ...

        // For simplicity, assume the access token is directly returned as a string
        // In reality, you should parse the JSON response to extract the token
        return "your_access_token"; // Placeholder for actual token retrieval logic
    }
}